<template>
  <el-dialog
    :title="dialogTiltle"
    :visible.sync="dialogVisible"
    class="dialogStyleMiddle"
    :before-close="cancel"
    append-to-body
    :close-on-click-modal="false"
  >
    <div>
      <el-form ref="queryForm" :inline="true" label-width="80px" :model="queryParams" class="dialog-form">
        <el-row>
          <el-col :span="11">
            <el-form-item label="用户名称">
              <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="部门名称" prop="deptId">
              <treeselect
                v-model="queryParams.deptId"
                class="treeselectStyle"
                :searchable="true"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="请选择部门"
                no-options-text="暂无数据"
                :disable-branch-nodes="true"
                clear-value-text=""
                style="width: 225px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10" class="button-wrap">
        <el-col :span="1.5">
          <el-button v-clickForbidden icon="el-icon-search" size="mini" @click="handleQuery()">搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-clickForbidden icon="el-icon-refresh" size="mini" @click="resetQuery()">重置</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-thumb" size="mini">{{ choice }}</el-button>
        </el-col> -->
      </el-row>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="sysUserData"
        stripe
        class="table-list"
        tooltip-effect="dark"
        :row-key="getRowKey"
        max-height="330"
        style="width: 100%"
        size="mini"
        @selection-change="handleSelectionChange"
        @row-click="rowChecked"
      >
        <el-table-column type="selection" :reserve-selection="true" width="38" align="center" />
        <el-table-column
          prop="loginName"
          label="登录账号"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="userName"
          label="用户名称"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="deptName"
          label="部门"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="状态" min-width="60" align="center" prop="status" :formatter="statusFormat" />
        <el-table-column prop="createTime" min-width="150" :show-overflow-tooltip="true" label="创建时间" align="center" />
      </el-table>
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        :page-sizes="[8,15,20,50,100]"
        :page-count="queryParams.pageCount"
        @pagination="getList"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="cancel">取 消</el-button>
      <el-button size="medium" type="primary" :disabled="btnDisabled" @click="submitForm">保 存</el-button>
    </span>
  </el-dialog>
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getNoUserByRoleId, addRoleToUser } from '@/api/system/role/role-to-user'
// 获取部门菜单树
import { selectAllCompanyDeptTree } from '@/api/system/dept'
export default {
  components: {
    Treeselect
  },
  data() {
    return {
      dialogTiltle: '',
      dialogVisible: false,
      // 角色id
      roleId: '',
      // 储存被选中用户id的数组
      userIds: '',
      sysUserData: [],
      // 部门树选项
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      loading: false,
      // 选中表格对话框的存储的值
      multipleSelection: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 8,
        pageCount: 5,
        roleId: '',
        deptId: null,
        userName: '',
        status: '0'
      },
      normalizer(node) {
        // 去掉children=[]的children属性
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        }
      },
      // 创建时间数组
      dateRange: [],
      // 分页总条数
      total: 0,
      statusOptions: [],
      btnDisabled: false
    }
  },
  created() {
    // 状态
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data.rows
    })
  },
  methods: {
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    showUser(roleId) {
      this.resetForm()
      this.dialogTiltle = '角色分配用户'
      this.dialogVisible = true
      this.roleId = roleId
      // 设置查询条件中的roleId 为默认值
      this.queryParams.roleId = roleId
      // 根据角色查询选择的用户
      this.selectNoUserByRoleId()
      // 加载树形菜单
      this.selectDeptTree()
    },
    // 根据角色id查询该角色没有分配的用户
    selectNoUserByRoleId() {
      const user = this.queryParams
      getNoUserByRoleId(user).then(resp => {
        if (resp) {
          this.sysUserData = resp.data.rows
          this.total = resp.data.total
          this.$refs.multipleTable.clearSelection()
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 分页选中返回数据
    getRowKey(row) {
      return row.userId
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.selectNoUserByRoleId()
    },
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.checkIds(val)
    },
    // 获取选中的行数并且把值返回到父节点（roleDataScopeDet）
    checkIds(val) {
      let ids = ''
      for (let i = 0; i < val.length; i++) {
        ids += val[i].userId + ','
      }
      this.userIds = ids
    },
    getList() {
      this.selectNoUserByRoleId()
    },
    // 搜索方法
    handleQuery() {
      this.selectNoUserByRoleId()
    },
    // 清空搜索信息
    resetForm() {
      this.queryParams.userName = ''
      this.queryParams.deptId = null
    },
    // 重置
    resetQuery() {
      this.resetForm()
      this.handleQuery()
    },
    // 部门选择树列表
    selectDeptTree() {
      selectAllCompanyDeptTree().then(resp => {
        if (resp) {
          this.deptOptions = resp.data
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 角色添加用户确认按钮
    submitForm() {
      if (this.multipleSelection.length === 0) {
        this.msgWarning('请至少勾选一项，再进行操作')
      } else {
        const roleId = this.roleId
        const userIds = this.userIds.toString()
        // 添加
        this.btnDisabled = true
        addRoleToUser({ roleId: roleId, userIds: userIds }).then(resp => {
          if (resp) {
            this.dialogVisible = false
            this.userIds = ''
            this.btnDisabled = false
            // 调用父组件的list查询
            this.$parent.getList()
          } else {
            this.btnDisabled = false
            this.msgError(resp.message)
          }
        })
      }
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      this.resetForm()
      this.userIds = ''
      // 调用父组件的list查询
      this.btnDisabled = false
      this.$parent.getList()
    }

  }
}
</script>
<style scoped>
  .dialogStyleMiddle .el-dialog .el-select{
    width: 100px;
  }
  .treeselectStyle >>> .vue-treeselect__control .vue-treeselect__value-container .vue-treeselect__input-container{
    height: 30px!important;
  }
</style>
